package com.alinu.settings.web.controller;

import com.alinu.exception.LoginException;
import com.alinu.settings.domain.User;
import com.alinu.settings.service.UserService;
import com.alinu.settings.service.impl.UserServiceImpl;
import com.alinu.utils.MD5Util;
import com.alinu.utils.PrintJson;
import com.alinu.utils.ServiceFactory;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenzuwei
 * @date 2021/3/14
 * @description 用户控制器类
 */
public class UserController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) {
        // 利用模板模式动态选择访问的方法
        String path = request.getServletPath();
        assert path != null;
        switch (path) {
            case "/settings/user/login.do":
                login(request, response);
                break;
            case "/settings/user/getUserList.do":
                getUserList(request, response);
                break;
            default:
                break;
        }
    }

    private void getUserList(HttpServletRequest request, HttpServletResponse response) {
        UserService userService = (UserService) ServiceFactory.getService(new UserServiceImpl());

        List<User> userList = userService.getUserList();

        PrintJson.printJsonObj(response, userList);
    }

    /**
     * 登录方法
     *
     * @param request  请求
     * @param response 响应
     */
    private void login(HttpServletRequest request, HttpServletResponse response) {
        String loginAct = request.getParameter("loginAct");
        String loginPwd = request.getParameter("loginPwd");
        // 加密后的密码
        String encryptionPwd = MD5Util.getMD5(loginPwd);
        // 业务层开发，统一使用代理类形态的接口对象
        UserService userService = (UserService) ServiceFactory.getService(new UserServiceImpl());

        try {
            String ip = request.getRemoteHost();
            // 查询用户信息
            User user = userService.findByActAndPwd(loginAct, encryptionPwd, ip);
            // 登录成功
            request.getSession().setAttribute("user", user);
            PrintJson.printJsonResult(response, true);

        } catch (LoginException e) {
            String msg = e.getMessage();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("result", false);
            resultMap.put("msg", msg);
            PrintJson.printJsonObj(response, resultMap);
        }


    }
}
